package DesignPattern.PrototypePattern.demo2;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class PrototypeManager {

    private Map<Class<? extends Prototype>, Prototype> prototypes = new HashMap(); // 存放原型

    private ReadWriteLock lock = new ReentrantReadWriteLock(); // 读锁为共享锁，写锁为独享锁

    private static class Singleton {
        public static PrototypeManager prototypeManager = new PrototypeManager();
    }

    public static PrototypeManager getInstance() {
        return Singleton.prototypeManager;
    }

    public <T extends Prototype> void addPrototype(T prototype) {
        lock.writeLock().lock();
        Class prototypeClass = prototype.getClass();
        prototypes.put(prototypeClass, prototype);
        lock.writeLock().unlock();
    }

    public <T extends Prototype> T getPrototype(Class<T> prototypeClass) throws IOException, ClassNotFoundException {
        lock.readLock().lock();
        Prototype prototype = prototypes.get(prototypeClass);
        lock.readLock().unlock();

        return (T) prototype.deepClone();
    }

}
